<?php
/**
 * Album Picture Model
 *
 * @author hiscaler <hiscaler@gmail.com>
 * @link http://www.yuandot.com/
 * @copyright Copyright &copy; 2009-2010 Yuandot Information Technology CO.,LTD.
 * @license http://doit.yuandot.com/license/
 */

class AlbumPicture extends CActiveRecord {
    /**
     * The followings are the available columns in table '{{albums_pictures}}':
     * @var integer $id
     * @var integer $album_id
     * @var string $name
     * @var string $picture_saved_path
     * @var string $thumbnail_saved_path
     * @var integer $clicks_count
     * @var integer $order_pos
     * @var integer $created
     * @var integer $updated
     */

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{albums_pictures}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
            array('album_id, order_pos', 'required'),
            array('album_id, clicks_count, order_pos, created, updated', 'numerical', 'integerOnly' => true),
            array('status', 'boolean', 'trueValue' => 1, 'falseValue' => 0),
            array('name, picture_saved_path, thumbnail_saved_path', 'length', 'max' => 200),
            array('picture_saved_path', 'file', 'on' => 'insert',
                'allowEmpty' => false,
                'types' => 'jpg, jpeg, gif',
                'maxSize' => 1024 * 1024 * 10,
            ),
            array('summary, summary_formatted', 'safe'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
        return array(
            // 所属相册
            'owner' => array(self::BELONGS_TO, 'Album', 'album_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'Id',
            'album_id' => Yii::t('albumPicture', 'album_id'),
            'name' => Yii::t('albumPicture', 'name'),
            'picture_saved_path' => Yii::t('albumPicture', 'picture_saved_path'),
            'summary' => Yii::t('albumPicture', 'summary'),
            'summary_formatted' => Yii::t('albumPicture', 'summary_formatted'),
            'clicks_count' => Yii::t('common', 'clicks_count'),
            'order_pos' => Yii::t('common', 'order_pos'),
            'created' => Yii::t('common', 'created'),
            'updated' => Yii::t('common', 'updated'),
        );
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'created',
                'updateAttribute' => 'updated',
            )
        );
    }

    protected function beforeValidate() {
        parent::beforeValidate();
        $parser = new CMarkdownParser();
        $this->summary_formatted = $parser->safeTransform($this->summary);

        return true;
    }

    private $_original_picture_saved_path;
    public function afterFind() {
        $this->_original_picture_saved_path = $this->picture_saved_path;
    }    

    public function beforeSave() {
        parent::beforeSave();
        $uploading_file = CUploadedFile::getInstance($this, 'picture_saved_path');
        if (is_object($uploading_file) && get_class($uploading_file) === 'CUploadedFile') {
            if (!$this->isNewRecord) {
                $model = AlbumPicture::model()->findByPk($this->id);
                @unlink($model->picturePath);
                @unlink($model->thumbnailPath);
            }
            $filename = md5(time() . $this->album_id) . '.' . $uploading_file->getExtensionName();
            $this->picture_saved_path = $filename;
            $this->_original_picture_saved_path = $filename;
            
            // 获取文件名（不包括扩展名）
            $uploading_file->getName();
            $picture_name = substr($uploading_file->getName(), 0,
                    strlen($uploading_file->getName()) - strlen($uploading_file->getExtensionName()) - 1);
            if (trim($this->name) == '') {
                $this->name = $picture_name;
            }
            if (trim($this->summary) == '') {
                $this->summary = $picture_name;
                $parser = new CMarkdownParser();
                $this->summary_formatted = $parser->safeTransform($picture_name);
            }

            $uploading_file->saveAs(YHtml::uploadPath('album/', true) . $filename);

            Yii::import('application.extensions.helper.CAppHelper');
            $this->thumbnail_saved_path = CAppHelper::generateThumbnail('album', $filename, 100, 100);
        } else {
            $this->picture_saved_path = $this->_original_picture_saved_path;
        }
        
        return true;
    }

    public function afterDelete() {
        @unlink($this->picturePath);
        @unlink($this->thumbnailPath);
    }

    // get picture saved path
    public function getPicturePath() {
        return YHtml::uploadPath("album/{$this->picture_saved_path}");
    }

    // get picture file source
    public function getPictureSource() {
        return YHtml::mediaUrl("album/{$this->picture_saved_path}");
    }

    // get thumbnail saved path
    public function getThumbnailPath() {
        return YHtml::uploadPath("album/{$this->thumbnail_saved_path}");
    }

    // get picture file source
    public function getThumbnailSource() {
        return YHtml::mediaUrl("album/{$this->thumbnail_saved_path}");
    }
    
}